package com.jhd.fuzhou.util;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;

import androidx.annotation.NonNull;

import com.github.barteksc.pdfviewer.PDFView;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.Locale;

import static android.content.ContentValues.TAG;

public class DownloadStreamThread extends Thread {
    String urlStr;PDFView pdfView;
    final String targetFileAbsPath;ProgressDialog _dialog;Context context;

    public DownloadStreamThread(String urlStr, String targetFileAbsPath, ProgressDialog _dialog, Context context, PDFView pdfView) {
        this.urlStr = urlStr;
        this.targetFileAbsPath = targetFileAbsPath;
        this._dialog = _dialog;
        this.context = context;
        this.pdfView = pdfView;
    }

    @Override
    public void run() {
        super.run();
        int count;
        File targetFile = new File(context.getExternalFilesDir(null).getPath() + "/Download/");
        if (!targetFile.exists()) {
            targetFile.mkdirs();
        }
        try {
            URL url = new URL(urlStr);
            URLConnection connection = url.openConnection();
            connection.connect();
            int contentLength = connection.getContentLength();
            InputStream input = new BufferedInputStream(url.openStream());
            OutputStream output = new FileOutputStream(targetFileAbsPath);

            byte[] buffer = new byte[1024];
            long total = 0;
            while ((count = input.read(buffer)) != -1) {
                total += count;
                Log.d(TAG, String.format(Locale.CHINA, "Download progress: %.2f%%", 100 * (total / (double) contentLength)));
                output.write(buffer, 0, count);
            }
            output.flush();
            output.close();
            input.close();
            handler.sendEmptyMessage(0);
        } catch (Exception e) {
            Log.e(TAG, "run: ", e);
        }
    }
    Handler handler=new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            File file=new File(targetFileAbsPath);
            if(_dialog != null)_dialog.cancel();

            UploadFile.showPDF(pdfView,file,context);
        }
    };
}
